#!/bin/bash

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m'

# 备份目录
BAK_DIR="/etc/yum.repos.d/bak"

# 获取系统信息
get_os_info() {
    OS_NAME=$(grep -E '^NAME=' /etc/os-release | cut -d= -f2 | tr -d '"' | awk '{print $1}')
    VERSION_ID=$(grep -E '^VERSION_ID=' /etc/os-release | cut -d= -f2 | cut -d. -f1)
}

# 显示镜像菜单
show_mirror_menu() {
    echo -e "${GREEN}请选择要使用的镜像源:${NC}"
    echo "1) 阿里云"
    echo "2) 清华大学"
    echo "3) 中科大"
    echo "4) 华为云"
    echo -n -e "${YELLOW}请输入数字 (1-4): ${NC}"
    read MIRROR_CHOICE
}

# 根据用户选择设置镜像域名
set_mirror_url() {
    case "$MIRROR_CHOICE" in
        1)
            MIRROR_URL="mirrors.aliyun.com"
            ;;
        2)
            MIRROR_URL="mirrors.tuna.tsinghua.edu.cn"
            ;;
        3)
            MIRROR_URL="mirrors.ustc.edu.cn"
            ;;
        4)
            MIRROR_URL="mirrors.huaweicloud.com/repository"
            ;;
        *)
            echo -e "${RED}无效的选择，请重新运行脚本。${NC}"
            exit 1
            ;;
    esac
}

# 备份原有源文件
backup_sources() {
    echo -e "${GREEN}正在备份原有yum源配置...${NC}"
    mkdir -p $BAK_DIR
    mv /etc/yum.repos.d/*.repo $BAK_DIR/ 2>/dev/null
}

# CentOS 7 源配置
centos7_repo() {
    cat <<EOF > /etc/yum.repos.d/CentOS-Base.repo
[base]
name=CentOS-\$releasever - Base
baseurl=http://$MIRROR_URL/centos/\$releasever/os/\$basearch/
gpgcheck=1
gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-CentOS-7

[updates]
name=CentOS-\$releasever - Updates
baseurl=http://$MIRROR_URL/centos/\$releasever/updates/\$basearch/
gpgcheck=1
gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-CentOS-7

[extras]
name=CentOS-\$releasever - Extras
baseurl=http://$MIRROR_URL/centos/\$releasever/extras/\$basearch/
gpgcheck=1
gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-CentOS-7

[centosplus]
name=CentOS-\$releasever - Plus
baseurl=http://$MIRROR_URL/centos/\$releasever/centosplus/\$basearch/
gpgcheck=1
enabled=0
gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-CentOS-7
EOF
}

# CentOS 8 Stream 镜像源
centos8_repo() {
    cat <<EOF > /etc/yum.repos.d/CentOS-Linux-BaseOS.repo
[baseos]
name=CentOS Linux \$releasever - BaseOS
baseurl=http://$MIRROR_URL/centos/\$releasever/BaseOS/\$basearch/os/
gpgcheck=1
gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-centosofficial

[appstream]
name=CentOS Linux \$releasever - AppStream
baseurl=http://$MIRROR_URL/centos/\$releasever/AppStream/\$basearch/os/
gpgcheck=1
gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-centosofficial

[powertools]
name=CentOS Linux \$releasever - PowerTools
baseurl=http://$MIRROR_URL/centos/\$releasever/PowerTools/\$basearch/os/
gpgcheck=1
enabled=0
gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-centosofficial
EOF
}

# Rocky Linux / AlmaLinux / Oracle Linux
generic_repo() {
    OS_LOWER=$(echo "$OS_NAME" | tr '[:upper:]' '[:lower:]')
    BASE_REPO="https://$MIRROR_URL/${OS_LOWER}/\$releasever"
    GPG_KEY_PATH="/etc/pki/rpm-gpg/"

    cat <<EOF > /etc/yum.repos.d/${OS_NAME}-Base.repo
[baseos]
name=$OS_NAME \$releasever - BaseOS
baseurl=http://$MIRROR_URL/${OS_LOWER}/\$releasever/BaseOS/\$basearch/os/
gpgcheck=1
gpgkey=file://${GPG_KEY_PATH}/RPM-GPG-KEY-${OS_LOWER}

[appstream]
name=$OS_NAME \$releasever - AppStream
baseurl=http://$MIRROR_URL/${OS_LOWER}/\$releasever/AppStream/\$basearch/os/
gpgcheck=1
gpgkey=file://${GPG_KEY_PATH}/RPM-GPG-KEY-${OS_LOWER}

[crb]
name=$OS_NAME \$releasever - CRB
baseurl=http://$MIRROR_URL/${OS_LOWER}/\$releasever/CRB/\$basearch/os/
gpgcheck=1
enabled=0
gpgkey=file://${GPG_KEY_PATH}/RPM-GPG-KEY-${OS_LOWER}
EOF
}

# 安装 EPEL 源并换源
install_epel() {
    if [ "$VERSION_ID" -ge 8 ]; then
        echo -e "${GREEN}正在安装 epel-release...${NC}"
        dnf install -y epel-release
        sed -i 's/metalink/#metalink/' /etc/yum.repos.d/epel*.repo
        sed -i "s|https://download.fedoraproject.org/pub|http://$MIRROR_URL/fedora|g" /etc/yum.repos.d/epel*.repo
    fi
}

# 清理并重建缓存
rebuild_cache() {
    echo -e "${GREEN}清理并重建yum缓存...${NC}"
    yum clean all
    yum makecache
}

# 主函数
main() {
    clear
    echo -e "${GREEN}=== 自动更换 Yum 源脚本 ===${NC}"

    get_os_info

    echo -e "${GREEN}检测到系统: $OS_NAME, 版本: $VERSION_ID${NC}"

    show_mirror_menu
    set_mirror_url

    backup_sources

    case "$OS_NAME" in
        CentOS)
            if [ "$VERSION_ID" == "7" ]; then
                centos7_repo
            elif [ "$VERSION_ID" == "8" ]; then
                centos8_repo
            else
                echo -e "${RED}不支持的 CentOS 版本: $VERSION_ID${NC}"
                exit 1
            fi
            ;;
        Rocky)
            generic_repo
            ;;
        AlmaLinux)
            generic_repo
            ;;
        Oracle)
            generic_repo
            ;;
        *)
            echo -e "${RED}未识别的操作系统或不支持的发行版: $OS_NAME${NC}"
            exit 1
            ;;
    esac

    install_epel
    rebuild_cache

    echo -e "${GREEN}✅ 镜像源更换完成！${NC}"
}

main